package com.parking.mgr.useraccount.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.parking.mgr.common.constant.CommonConstant;
import com.parking.mgr.common.exception.LoginAuthException;
import com.parking.mgr.common.exception.enums.AuthExceptionEnum;
import com.parking.mgr.common.util.IdUtils;
import com.parking.mgr.useraccount.facede.LoginServiceFacede;
import com.parking.mgr.useraccount.facede.UserServiceFacede;
import com.parking.mgr.useraccount.model.entity.LoginAuthEntity;
import com.parking.mgr.useraccount.model.entity.UserInfoEntity;
import com.parking.mgr.useraccount.model.mapper.LoginAuthMapper;
import com.parking.mgr.useraccount.model.mapstruct.LoginAuthMapStruct;
import com.parking.mgr.useraccount.model.param.LoginAuthParam;
import com.parking.mgr.useraccount.model.vo.AuthUserInfoVO;
import com.parking.mgr.useraccount.model.vo.LoginAuthVO;
import com.parking.mgr.useraccount.service.LoginAuthService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LoginAuthServiceImpl
 * @Description 登录授权
 * @Auther: zhijianpu
 * @Date: 2023/5/26
 */
@Log4j2
@Service
public class LoginAuthServiceImpl extends ServiceImpl<LoginAuthMapper, LoginAuthEntity> implements LoginAuthService {

    @Resource
    private LoginServiceFacede loginServiceFacede;

    @Resource
    private UserServiceFacede userServiceFacede;

    @Resource
    private LoginAuthMapper loginAuthMapper;

    @Resource
    private LoginAuthMapStruct loginAuthMapStruct;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> getAuthCode(HttpServletRequest request) {
        String token = request.getHeader(CommonConstant.LOGIN_TOKEN);
        String clientId =  request.getHeader(CommonConstant.CLIENT_ID);
        // 获取token的ID
        String tokenId = loginServiceFacede.getTokenId(token, clientId);
        // 生成授权码
        String authCode = IdUtils.getId();
        // 过期时间5分钟
        Long expireTime = 5 * 60 * 1000L;

        LoginAuthEntity loginAuthEntity = new LoginAuthEntity();
        loginAuthEntity.setFkLoginTokenId(tokenId);
        loginAuthEntity.setFLoginToken(token);
        loginAuthEntity.setFClientId(clientId);
        loginAuthEntity.setFCode(authCode);
        loginAuthEntity.setFExpireTimeMillis(expireTime);
        loginAuthEntity.setId(IdUtils.getId());
        this.save(loginAuthEntity);

        Map<String, Object> authCodeMap = new HashMap<>();
        authCodeMap.put("fCode", authCode);

        return authCodeMap;
    }

    @Override
    public AuthUserInfoVO getLoginUserInfo(String fCode) {
        AuthUserInfoVO authUserInfoVO = new AuthUserInfoVO();
        // 获取授权对象
        LoginAuthEntity loginAuthEntity = loginAuthMapper.selectOne(new LambdaQueryWrapper<LoginAuthEntity>()
                .eq(LoginAuthEntity::getFCode, fCode));

        if (ObjectUtil.isNull(loginAuthEntity)) {
            throw new LoginAuthException(AuthExceptionEnum.LOGIN_EXPIRED.getMessage());
        }

        String loginToken = loginAuthEntity.getFLoginToken();
        String clientId = loginAuthEntity.getFClientId();

        // 获取用户账号ID
        String passportId = loginServiceFacede.queryPassportByClientIdToken(loginToken, clientId);
        // 根据用户账号ID获取用户信息
        UserInfoEntity userInfoEntity = userServiceFacede.getUserInfoByPassportId(passportId);

        BeanUtil.copyProperties(userInfoEntity, authUserInfoVO);
        authUserInfoVO.setClientId(clientId);
        authUserInfoVO.setLoginToken(loginToken);
        authUserInfoVO.setFHeadImgId(userInfoEntity.getFHeadImgFileId());

        return authUserInfoVO;
    }

    @Override
    public IPage<LoginAuthVO> list(LoginAuthParam loginAuthParam) {
        log.info("获取登录授权列表");
        LambdaQueryWrapper<LoginAuthEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(loginAuthParam.getFClientId())) {
            log.info("根据客户端ID查询登录授权");
            queryWrapper.eq(LoginAuthEntity::getFClientId, loginAuthParam.getFClientId());
        }

        IPage<LoginAuthVO> loginAuthList = loginAuthMapStruct.entity2VO(this.page(new Page<>(loginAuthParam.getCurrPage(), loginAuthParam.getPageSize()), queryWrapper));

        return loginAuthList;
    }


}
